<template>
  <div class="add-report-container">
    <el-tabs v-model="activeTab" class="add-report-tabs">
      <el-tab-pane :label="t('addReport.tabs.uploadNew')" name="upload">
        <div class="upload-container">
          <!-- 上传区域 -->
          <div class="upload-area p-6">
            <div class="upload-content">
              <div class="upload-icon">
                <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
                  <rect width="64" height="64" rx="8" fill="#E3F2FD" />
                  <path
                    d="M20 44V20C20 18.8954 20.8954 18 22 18H32L42 28V44C42 45.1046 41.1046 46 40 46H22C20.8954 46 20 45.1046 20 44Z"
                    fill="#2196F3"
                  />
                  <path
                    d="M32 18V28H42"
                    stroke="#1976D2"
                    stroke-width="2"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M26 34H36M26 38H34"
                    stroke="white"
                    stroke-width="2"
                    stroke-linecap="round"
                  />
                </svg>
              </div>

              <div class="upload-text">
                <!-- <p class="main-text">
                  {{ t("addReport.uploadArea.dragText") }}
                </p> -->
                <div class="upload-tips">
                  <p>{{ t("addReport.uploadArea.supportedFormats") }}</p>
                </div>
              </div>
              <!-- 单选按钮组 体检报告、急症报告、住院报告 -->
              <div class="radio-group mb-2 flex items-center">
                <span class="text-sm text-gray-500 mr-6 source-label">
                  报告来源</span
                >
                <el-radio-group v-model="reportType">
                  <el-radio
                    v-for="item in healthTypeList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </el-radio>
                </el-radio-group>
              </div>
            </div>

            <el-upload
              v-model:file-list="fileList"
              class="upload-demo flex justify-center w-full mb-6"
              :auto-upload="false"
              multiple
              :accept="accept"
              :before-upload="handleBeforeUpload"
              :on-change="handleFileChange"
              :show-file-list="false"
            >
              <el-button type="primary">
                {{ t("addReport.uploadArea.uploadButton") }}
              </el-button>
            </el-upload>

            <!-- 上传队列标题 -->
            <div v-if="fileList.length > 0" class="upload-queue-header">
              <h3 class="queue-title">{{ t("addReport.queue.title") }}</h3>
              <div class="queue-options">
                <el-checkbox v-model="urgentProcess">
                  {{ t("addReport.queue.urgentProcess") }}
                </el-checkbox>
              </div>
            </div>
            <!-- 选中的文件列表 -->
            <div v-if="fileList.length > 0" class="file-grid">
              <div v-for="file in fileList" :key="file.uid" class="file-card">
                <div class="file-icon-wrapper">
                  <div
                    class="file-type-icon"
                    :class="getFileTypeClass(file.name)"
                  >
                    {{ getFileTypeLabel(file.name) }}
                  </div>
                  <el-button
                    v-if="file.status !== 'uploading'"
                    class="remove-btn"
                    size="small"
                    type="text"
                    @click="removeFile(file)"
                  >
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>

                <div class="file-info">
                  <div class="file-name" :title="file.name">
                    {{ file.name }}
                  </div>
                  <div class="file-size">
                    {{ formatFileSize(file.size || 0) }}
                  </div>
                </div>

                <!-- 进度条 -->
                <div v-if="file.status === 'uploading'" class="file-progress">
                  <el-progress
                    :percentage="file.percentage || 0"
                    :stroke-width="4"
                    :show-text="false"
                    :color="getProgressColor(file.percentage || 0)"
                  />
                  <div class="progress-text">{{ file.percentage || 0 }}%</div>
                </div>
                <!-- 状态显示 -->
                <div
                  v-else-if="file.status === 'success'"
                  class="file-status success"
                >
                  {{ t("addReport.fileStatus.success") }}
                </div>
                <div
                  v-else-if="file.status === 'fail'"
                  class="file-status error"
                >
                  {{ t("addReport.fileStatus.failed") }}
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div v-if="fileList.length > 0" class="upload-actions">
            <el-button
              type="primary"
              :disabled="fileList.length === 0"
              :loading="uploading"
              @click="handleUpload"
            >
              {{
                uploading
                  ? t("addReport.fileStatus.uploading")
                  : t("addReport.buttons.startUpload")
              }}
            </el-button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="t('addReport.tabs.uploaded')" name="uploaded">
        <div class="uploaded-container">
          <uploadC ref="uploadCRef" />
        </div>
      </el-tab-pane>
      <el-tab-pane :label="t('addReport.tabs.logs')" name="logs">
        <operationLog v-if="activeTab === 'logs'" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { reportApi } from "@/api/report-api";
import { useToolsStore } from "@/store/modules/tools";
import { EXTENSION_TO_MIME, formatFileSize } from "@/utils/fileTypeConfig";
import { Close } from "@element-plus/icons-vue";
import type { UploadFile, UploadFiles } from "element-plus";
import { ElMessage } from "element-plus";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import operationLog from "./operationLog.vue";
import uploadC from "./uploadC.vue";

// 当前激活的标签页
const activeTab = ref("upload");
const uploadCRef = ref();
const reportType = ref(1);

// 国际化
const { t } = useI18n();

// 监听标签页变化
watch(activeTab, newVal => {
  if (newVal === "uploaded" && uploadCRef.value) {
    // 当切换到已上传报告标签时，调用子组件的激活方法
    uploadCRef.value.handleActivated();
  }
});

// 报告类型
const healthTypeList = computed(() => {
  return useToolsStore().getDictData().healthTypeList || [];
});

// 文件上传相关
const uploadRef = ref();
const fileList = ref<UploadFiles>([]);
const uploading = ref(false);

// 上传选项
const urgentProcess = ref(false);

// 允许的文件类型
const accept = ".pdf,.jpg,.jpeg,.png,.dcm";

// 进度条颜色
const progressColor = computed(() => {
  return [
    { color: "#f56c6c", percentage: 20 },
    { color: "#e6a23c", percentage: 40 },
    { color: "#5cb87a", percentage: 60 },
    { color: "#1989fa", percentage: 80 },
    { color: "#6f7ad3", percentage: 100 }
  ];
});

// 根据文件扩展名获取文件类型标签
const getFileTypeLabel = (fileName: string) => {
  const extension = fileName.split(".").pop()?.toLowerCase();
  switch (extension) {
    case "pdf":
      return "PDF";
    case "jpg":
    case "jpeg":
      return "JPG";
    case "png":
      return "PNG";
    case "dcm":
    case "dicom":
      return "DICOM";
    case "doc":
    case "docx":
      return "WORD";
    default:
      return "FILE";
  }
};

// 根据文件类型获取样式类名
const getFileTypeClass = (fileName: string) => {
  const extension = fileName.split(".").pop()?.toLowerCase();
  switch (extension) {
    case "pdf":
      return "file-pdf";
    case "jpg":
    case "jpeg":
    case "png":
      return "file-image";
    case "dcm":
    case "dicom":
      return "file-dicom";
    case "doc":
    case "docx":
      return "file-word";
    default:
      return "file-default";
  }
};

// 根据进度获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 30) return "#409EFF";
  if (percentage < 70) return "#E6A23C";
  return "#67C23A";
};

// 文件上传前的验证
const handleBeforeUpload = (file: File) => {
  // 检查文件类型
  const allowedTypes = [".pdf", ".jpg", ".jpeg", ".png", ".dcm"];
  const extension = "." + file.name.split(".").pop()?.toLowerCase();
  if (!allowedTypes.includes(extension)) {
    ElMessage.error(t("addReport.messages.unsupportedFileType"));
    return false;
  }

  // 检查文件大小（限制为 100MB）
  const isPdf = file.type === EXTENSION_TO_MIME[".pdf"];
  const maxSize = isPdf ? 100 * 1024 * 1024 : 20 * 1024 * 1024;

  if (file.size > maxSize) {
    ElMessage.error(t("addReport.messages.fileSizeLimit"));
    return false;
  }

  return true;
};

// 文件状态改变时的回调
const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  if (file.status === "ready") {
    fileList.value = files;
  }
};

// 移除文件
const removeFile = (file: UploadFile) => {
  const index = fileList.value.findIndex(item => item.uid === file.uid);
  if (index > -1) {
    fileList.value.splice(index, 1);
  }
};

// 处理单个文件上传
const handleUploadFile = async (file: UploadFile): Promise<string> => {
  if (!file.raw) {
    throw new Error(t("addReport.messages.invalidFileObject"));
  }

  try {
    file.status = "uploading";
    file.percentage = 0;

    // 准备预签名URL的请求参数
    const params = {
      fileName: file.name,
      fileType: 1 // 文件类型，这里固定为1
    };

    // 获取预签名URL
    const presignedResponse = await reportApi.presignedApi(params);

    if (!presignedResponse?.data?.presignedUrl) {
      throw new Error(t("addReport.messages.getUploadUrlFailed"));
    }

    // 创建进度更新定时器
    const progressTimer = setInterval(() => {
      if (file.percentage! < 90) {
        file.percentage = Math.min(file.percentage! + Math.random() * 20, 90);
      }
    }, 200);

    try {
      // 使用预签名URL上传文件
      const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
        method: "PUT",
        body: file.raw,
        headers: {
          "Content-Type": file.raw.type || "application/octet-stream"
        }
      });

      if (!uploadResponse.ok) {
        throw new Error(
          `上传失败: ${uploadResponse.status} ${uploadResponse.statusText}`
        );
      }

      // 清理进度定时器并设置100%进度
      clearInterval(progressTimer);
      file.percentage = 100;
      file.status = "success";

      // 返回文件的 objectKey，用于后续的报告上传
      return presignedResponse.data.objectKey;
    } catch (error) {
      clearInterval(progressTimer);
      throw error;
    }
  } catch (error) {
    console.error(t("addReport.messages.fileUploadFailed"), error);
    file.status = "fail";
    throw error;
  }
};

// 处理文件上传
const handleUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning(t("addReport.messages.selectFilesFirst"));
    return;
  }

  uploading.value = true;

  try {
    // 记录上传开始的日志
    console.log(t("addReport.messages.uploadStarted"), {
      fileCount: fileList.value.length,
      urgentProcess: urgentProcess.value
    });

    // 存储所有上传文件的 objectKey
    const objectKeys: string[] = [];

    // 逐个上传文件
    for (const file of fileList.value) {
      if (!handleBeforeUpload(file.raw)) {
        continue;
      }
      console.log(
        t("addReport.messages.fileUploadStarted", { fileName: file.name })
      );
      try {
        const objectKey = await handleUploadFile(file);
        objectKeys.push(objectKey);
        console.log(
          t("addReport.messages.fileUploadCompleted", {
            fileName: file.name,
            objectKey
          })
        );
      } catch (error) {
        console.error(
          t("addReport.messages.fileUploadError", { fileName: file.name }),
          error
        );
        // 继续上传其他文件
      }
    }

    // 检查是否有文件上传成功
    if (objectKeys.length === 0) {
      throw new Error(t("addReport.messages.noFilesUploaded"));
    }

    // 提交报告信息
    const reportData = {
      emergencyProcess: urgentProcess.value,
      reportFileList: objectKeys.map((key, i) => ({
        resourceName: fileList.value[i].name,
        resourceObjectKey: key
      })),
      reportType: reportType.value // 默认报告类型，根据实际需求修改
    };

    // 调用报告上传 API
    await reportApi.reportUpload(reportData);

    ElMessage.success(t("addReport.messages.uploadSuccess"));

    // 记录上传完成的日志
    console.log(t("addReport.messages.uploadCompleted"), {
      successCount: fileList.value.filter(f => f.status === "success").length,
      totalCount: fileList.value.length,
      objectKeys
    });

    // 清空文件列表
    fileList.value = [];
  } catch (error) {
    console.error(t("addReport.messages.fileUploadFailed"), error);
    ElMessage.error(
      error instanceof Error
        ? error.message
        : t("addReport.messages.uploadFailed")
    );
  } finally {
    uploading.value = false;
  }
};
</script>

<style lang="scss">
.add-report-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;

  .el-tabs__nav {
    background-color: transparent !important;
  }
  .el-tabs__nav-wrap:after {
    height: 1px;
    background-color: #f5f5f5;
  }
  .upload-container {
    margin: 0 auto;
  }

  .upload-area {
    margin-bottom: 30px;
    border: 2px dashed #dcdfe6;

    :deep(.el-upload-dragger) {
      width: max-content;
      height: auto;
      border: none;
      border-radius: 8px;
      background: #fafafa;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
      position: relative;

      &:hover {
        border-color: #409eff;
        background: #f0f9ff;
      }
    }

    .upload-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30px 20px;

      .upload-icon {
        margin-bottom: 16px;
      }

      .upload-text {
        text-align: center;
        margin-bottom: 20px;

        .main-text {
          font-size: 16px;
          color: #303133;
          margin-bottom: 12px;
          font-weight: 500;
        }

        .upload-tips {
          color: #909399;
          font-size: 14px;
          line-height: 2;
          white-space: pre-wrap;
          text-align: left;
        }
      }

      .source-label {
        &::before {
          content: "*";
          color: #f56c6c;
        }
      }

      .upload-btn {
        font-size: 14px;
        padding: 8px 24px;
      }
    }
  }

  // 上传队列头部
  .upload-queue-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;

    .queue-title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      margin: 0;
    }

    .queue-options {
      display: flex;
      gap: 20px;

      :deep(.el-checkbox) {
        .el-checkbox__label {
          font-size: 14px;
        }
      }
    }
  }

  // 文件网格布局
  .file-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, 50%);
    gap: 16px;
    margin-bottom: 30px;
  }

  // 文件卡片
  .file-card {
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 16px;
    position: relative;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .file-icon-wrapper {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      margin-bottom: 12px;

      .file-type-icon {
        width: 48px;
        height: 48px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        color: white;

        &.file-pdf {
          background: #ff6b6b;
        }

        &.file-image {
          background: #4ecdc4;
        }

        &.file-dicom {
          background: #45b7d1;
        }

        &.file-word {
          background: #96ceb4;
        }

        &.file-default {
          background: #95a5a6;
        }
      }

      .remove-btn {
        padding: 4px;
        color: #c0c4cc;

        &:hover {
          color: #f56c6c;
        }
      }
    }

    .file-info {
      margin-bottom: 12px;

      .file-name {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .file-size {
        font-size: 12px;
        color: #909399;
      }
    }

    .file-progress {
      .progress-text {
        text-align: right;
        font-size: 12px;
        color: #409eff;
        margin-top: 4px;
      }
    }

    .file-status {
      font-size: 12px;
      text-align: center;
      padding: 4px 8px;
      border-radius: 4px;

      &.success {
        color: #67c23a;
        background: #f0f9ff;
      }

      &.error {
        color: #f56c6c;
        background: #fef0f0;
      }
    }
  }

  .upload-actions {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .el-button {
      padding: 10px 32px;
      font-size: 14px;
    }
  }
}
</style>
